package com.plugin.storage.conf;

import com.plugin.storage.base.SdkContext;
import com.plugin.storage.base.StorageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static java.util.stream.Collectors.toList;

@ConfigurationProperties(prefix = "storage.sdk")
public class SdkConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(SdkConfig.class);

    private List<SdkContext> contexts = new ArrayList<>();

    public List<SdkContext> getContexts() {
        return contexts;
    }

    public void setContexts(List<SdkContext> contexts) {
        this.contexts = contexts;
    }

    public List<SdkContext> getContext(String... types) {
        if (types == null) {
            return getContexts();
        }
        List<String> typeList = Arrays.asList(types);
        if (typeList.isEmpty()) {
            return getContexts();
        }
        List<SdkContext> contexts = getContexts().stream()
                .filter(e -> typeList.stream().anyMatch(t -> e.getAlias().startsWith(t)))
                .collect(toList());
        if (contexts.isEmpty()) {
            throw new StorageException("sdk context not found.");
        }
        return contexts;
    }

    public SdkContext getContext(String type) {
        if (type == null) {
            return getContexts().stream().findAny().orElseThrow(() -> new StorageException("sdk context not found."));
        }
        return getContexts().stream()
                .filter(e -> e.getAlias().startsWith(type))
                .findFirst()
                .orElseThrow(() -> new StorageException("sdk context not found."));
    }
}
